﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using BFlatCompile.Nodes;

namespace BFlatCompile.Serializer
{
	internal static class Phase15FindMain
	{
		public static string Do(Compiler compiler, IList<Method> staticMethods, Dictionary<object, object> parentLookup, Dictionary<string, int> startLocations)
		{
			int mainMethodLocationInt = -1;
			if (Variable.Table.HasId("main") && Variable.Table.HasId("Program"))
			{
				int mainNameId = Variable.Table.GetId("main");
				int programNameId = Variable.Table.GetId("Program");

				foreach (Method m in staticMethods)
				{
					if (m.NameIndex == mainNameId)
					{
						Class c = parentLookup[m] as Class;
						if (c != null && c.NameIndex == programNameId)
						{
							if (mainMethodLocationInt != -1)
							{
								throw new ParserException("Multiple Program.main() methods were found.");
							}

							if (m.Params.Length != 0)
							{
								throw new ParserException("Program.main() must not accept any arguments.");
							}

							mainMethodLocationInt = startLocations["M" + m.ID];
						}
					}
				}
			}
			if (mainMethodLocationInt == -1)
			{
				throw new ParserException("No Program.main() method");
			}
			return Util.ToHex(compiler, mainMethodLocationInt);
		}
	}
}
